package hyg.q4;
public class Main
{
    public static void main(String[] args)
    {
        int[] result=new int[8];
        getResult(0,result);
    }
    //使用递归求出3^8种情况
    public static void getResult(int index,int[] result){
        if(index==8){
            showResult(result);//根据数组的取值转换成表达式，且求值，这方法有待改进，写的很乱
            return;
        }
        //每个空有三种可能，0,1,2
        for(int i=0;i<3;i++){
            result[index]=i;
            getResult(index+1,result);
            result[index]=0; //恢复原来的状态
        }
    }
    public static void showResult(int[] result){

        int sum=0;
        char operateChar='+';
        String[] source=new String[]{"9","8","7","6","5","4","3","2","1"};
        StringBuilder expression=new StringBuilder();
        StringBuilder number=new StringBuilder();
        number.append(source[0]);

        expression.append(source[0]);

        for(int i=0;i<result.length;i++){
            if(result[i]==0){//如果为0，表示数字合并
                number.append(source[i+1]);
                expression.append(source[i+1]);
            }else if(result[i]==1){
                sum=calc(operateChar,sum,number);
                operateChar='+';
                number.append(source[i+1]);
                expression.append("+").append(source[i+1]);
            }else if(result[i]==2){
                sum=calc(operateChar,sum,number);
                operateChar='-';
                number.append(source[i+1]);
                expression.append("-").append(source[i+1]);
            }
        }
        sum=calc(operateChar,sum,number);
        if(sum==100){
            System.out.print(expression.toString()+"=100");
            System.out.println();
        }
    }
    public static int calc(char operator,int sum,StringBuilder number){
        if(operator=='+'){
            sum+=Integer.parseInt(number.toString());
            number.delete(0, number.length());
        }else if(operator=='-'){
            sum-=Integer.parseInt(number.toString());
            number.delete(0, number.length());
        }
        return sum;
    }
}